package com.smit.update.activity;

import android.content.Context;
import android.os.Bundle;
import android.os.PowerManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.smit.bean.UpdatePackageBean;
import com.smit.update.R;
import com.smit.utils.SharePrefUtil;
import com.smit.utils.StrUtil;

import java.io.File;
import java.util.Locale;

import static com.smit.utils.StrUtil.getFileSizeStr;

public class UpdateActivity extends BaseActivity {
    final String TAG = "UpdateActivity";
    private Button cancelButton;
    private Button downloadButton;
    private TextView fileNameTextView;
    private TextView detailTextView;
    private ProgressBar downloadProgressBar;
    private TextView downloadTextView;
    private boolean isDownloading = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update);
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        fileNameTextView = (TextView) findViewById(R.id.file_name);
        detailTextView = (TextView) findViewById(R.id.update_detail);
        downloadProgressBar = (ProgressBar) findViewById(R.id.download_prog);
        downloadTextView = (TextView) findViewById(R.id.download_text);

        cancelButton = (Button) findViewById(R.id.cancel_button);
        cancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                UpdateActivity.this.finish();
            }
        });

        downloadButton = (Button) findViewById(R.id.ok_button);
        downloadButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                downloadFile();
            }
        });
        if(!updateNow()) {
            initViews();
        }
    }

    private boolean updateNow(){
        boolean confirm = getIntent().getBooleanExtra("confirm", true);//开机启动的时候回自动升级
        if (!confirm) {//启动后直接进入升级
            Log.d(TAG, "start update without confirm");
            downloadProgressBar.setVisibility(View.INVISIBLE);
            String updateFilePath = SharePrefUtil.getString(this, SharePrefUtil.DOWNLOAD_FILE_PATH, "");
            updateManager.startOSUpdate(updateFilePath, false);
            return true;
        }
        return false;
    }

    private void initViews() {
        UpdatePackageBean updatePackageInfo = updateManager.getUpdatePackageBean();
        if (updatePackageInfo == null) {
            Log.d(TAG, "updatePackageInfo is null");
            return;
        }
        fileNameTextView.setText(updatePackageInfo.getFilename());
        String sizeStr = getFileSizeStr(updatePackageInfo.getSize());
        String type = updatePackageInfo.getType();
        String typeStr = (type.equals("entire") ? "整包升级" : "差分升级");
        String versionStr = updatePackageInfo.getToVersion();
        String description = updatePackageInfo.getDescription();
        detailTextView.setText("大小：" + sizeStr + "\n"
                + "版本：" + versionStr + "\n"
                + "类型：" + typeStr + "\n"
                + "描述：" + description); //+ "\n" + updatePackageInfo.toString()

        long downloadSize = 0;
        final String downloadPath = updateManager.getDownloadPath();
        File file = new File(downloadPath);
        if (file.exists()) {
            downloadSize = file.length();
        }
        if (updatePackageInfo.getSize() == downloadSize) {
            downloadButton.setText(R.string.btn_update);
            downloadProgressBar.setProgress(100);
            updateManager.startOSUpdate(downloadPath, true);
        }
    }

    /*
    * 利用xUtils进行断点续传下载
    */
    private void downloadFile() {
        //没有下载时点击,进行下载
        if (!isDownloading) {
            updateManager.cancelDownload();//先取消后台或者其他地方的下载
            isDownloading = true;
            RequestCallBack<File> requestCallBack = new RequestCallBack<File>() {
                @Override
                public void onStart() {
                }

                @Override
                public void onLoading(long total, long current, boolean isUploading) {
                    downloadProgressBar.setProgress((int) ((current * 100) / total));
                    String currentSize = StrUtil.getFileSizeStr(current);
                    String totalSize = StrUtil.getFileSizeStr(total);
                    String percentStr = String.format(Locale.getDefault(), "%d%%", current * 100 / total);
                    downloadTextView.setText(percentStr + "  " + currentSize + "/" + totalSize);
                    Log.d(TAG, "update file downloaded " + percentStr);
                }

                @Override
                public void onSuccess(ResponseInfo<File> responseInfo) {
                    updateManager.startOSUpdate(responseInfo.result.getPath(), true);
                }

                @Override
                public void onFailure(HttpException error, String msg) {
                    detailTextView.setText(msg);
                    Toast.makeText(UpdateActivity.this, "下载失败", Toast.LENGTH_LONG).show();
                }
            };
            updateManager.downloadFile(requestCallBack);
        }
    }


}


